package com.kdzy.lshy.common_server.common.wechart;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * http访问url
 * 
 * @author cly
 */
public class VisitUrl {
	public static void main(String[] args) {
		// 发送 GET 请求
		// String s=VisitUrl.sendGet("http://...com"+"p1=1&p2=2");
		// System.out.println(s);

		// 发送 POST 请求
		String sr = VisitUrl.sendPost(
				"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx126aa425932c5906&redirect_uri=https://www.baidu.com&response_type=code&scope=snsapi_base&state=1#wechat_redirect",
				"");
		System.out.println(sr);
	}

	/**
	 * 简单访问url获取结果 http
	 * 
	 * @author zl 20172017年9月1日上午10:52:18
	 * @param url
	 * @return String
	 */
	public static String visitUrl(String url) {
		// 访问url
		String jsonResulet = "";
		try {
			String str;
			URL u = new URL(url);
			InputStream is = u.openStream();
			InputStreamReader isr = new InputStreamReader(is, "UTF-8");
			BufferedReader br = new BufferedReader(isr);
			if (br.ready()) {
				while ((str = br.readLine()) != null) {
					jsonResulet += str;
				}
			}
			br.close();
			isr.close();
			is.close();
		} catch (MalformedURLException e) {
			// url地址错误
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return jsonResulet;
	}

	/**
	 * 向指定URL发送GET方法的请求 http
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		String urlNameString = null;
		BufferedReader in = null;
		try {
			if (null == param) {
				urlNameString = url;
			} else {
				urlNameString = url + "?" + param;
			}
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("Accept-Charset", "utf-8");
			connection.setRequestProperty("contentType", "utf-8");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			// Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			// for (String key : map.keySet()) {
			// System.out.println(key + "--->" + map.get(key));
			// }
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			// System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求 http
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("Accept-Charset", "utf-8");
			conn.setRequestProperty("contentType", "utf-8");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			// System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * https POST 访问
	 */
	public static String sendHttps(String url, String param) throws IOException {

		SSLContext ctx = null;
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			ctx = SSLContext.getInstance("TLS");
			ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		SSLSocketFactory ssf = ctx.getSocketFactory();

		URL u = new URL(url);
		HttpsURLConnection httpsConn = (HttpsURLConnection) u.openConnection();
		httpsConn.setSSLSocketFactory(ssf);
		httpsConn.setHostnameVerifier(new HostnameVerifier() {
			@Override
			public boolean verify(String arg0, SSLSession arg1) {
				return true;
			}
		});
		// 设置通用的请求属性
		httpsConn.setRequestProperty("accept", "*/*");
		httpsConn.setRequestProperty("Accept-Charset", "utf-8");
		httpsConn.setRequestProperty("contentType", "utf-8");
		httpsConn.setRequestProperty("connection", "Keep-Alive");
		httpsConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

		// 发送POST请求必须设置如下两行
		httpsConn.setDoInput(true);
		httpsConn.setDoOutput(true);
		// 获取URLConnection对象对应的输出流
		out = new PrintWriter(new OutputStreamWriter(httpsConn.getOutputStream(), "utf-8"));
		// 发送请求参数
		out.print(param);
		// flush输出流的缓冲
		out.flush();
		// 定义BufferedReader输入流来读取URL的响应
		in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(), "UTF-8"));
		String line;
		while ((line = in.readLine()) != null) {
			result += line;
		}
		if (out != null) {
			out.close();
		}

		return result;
	}

	/**
	 * https GET 访问
	 */
	public static String sendHttpsGet(String url, String param) throws IOException {

		SSLContext ctx = null;
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			ctx = SSLContext.getInstance("TLS");
			ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		SSLSocketFactory ssf = ctx.getSocketFactory();

		if (null == param) {
			url = url;
		} else {
			url = url + "?" + param;
		}

		URL u = new URL(url);
		HttpsURLConnection httpsConn = (HttpsURLConnection) u.openConnection();
		httpsConn.setSSLSocketFactory(ssf);
		httpsConn.setHostnameVerifier(new HostnameVerifier() {
			@Override
			public boolean verify(String arg0, SSLSession arg1) {
				return true;
			}
		});
		// 设置通用的请求属性
		httpsConn.setRequestProperty("accept", "*/*");
		httpsConn.setRequestProperty("Accept-Charset", "utf-8");
		httpsConn.setRequestProperty("contentType", "utf-8");
		httpsConn.setRequestProperty("connection", "Keep-Alive");
		httpsConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

		// 建立实际的连接
		httpsConn.connect();

		// 定义BufferedReader输入流来读取URL的响应
		in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(), "UTF-8"));
		String line;
		while ((line = in.readLine()) != null) {
			result += line;
		}
		if (out != null) {
			out.close();
		}

		return result;
	}

	private static class DefaultTrustManager implements X509TrustManager {
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	}

	/**
	 * 从url下载图片并返回其byte[]
	 * 
	 * @author zl 2018年1月16日 上午11:24:53
	 * @param urlPath
	 * @return byte[]
	 */
	public static byte[] getImageFromURL(String urlPath) {
		byte[] data = null;
		InputStream is = null;
		HttpURLConnection conn = null;
		try {
			URL url = new URL(urlPath);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			// conn.setDoOutput(true);
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(6000);
			is = conn.getInputStream();
			//conn.getContentType();
			if (conn.getResponseCode() == 200) {
				data = readInputStream(is);
			} else {
				data = null;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			conn.disconnect();
		}
		return data;
	}

	/**
	 * 读取InputStream数据，转为byte[]数据类型
	 * 
	 * @param is
	 *            InputStream数据
	 * @return 返回byte[]数据
	 */
	public static byte[] readInputStream(InputStream is) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int length = -1;
		try {
			while ((length = is.read(buffer)) != -1) {
				baos.write(buffer, 0, length);
			}
			baos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] data = baos.toByteArray();
		try {
			is.close();
			baos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}

	/**
	 * 根据url下载文件，参数（文件网址，存文件的本地地址）
	 * 
	 * @author zl 2018年1月16日 上午11:11:59
	 * @param urlString
	 * @param filePath
	 * @return
	 */
	public static Boolean downloadFile(String urlString, String filePath) {
		// 构造URL
		URL url;
		try {
			url = new URL(urlString);
			// 打开连接
			URLConnection con;
			try {
				con = url.openConnection();
				// 输入流
				InputStream is = con.getInputStream();
				// 1K的数据缓冲
				byte[] bs = new byte[1024];
				// 读取到的数据长度
				int len;
				// 输出的文件流
				OutputStream os = new FileOutputStream(filePath);
				// 开始读取
				while ((len = is.read(bs)) != -1) {
					os.write(bs, 0, len);
				}
				// 完毕，关闭所有链接
				os.close();
				is.close();
				return true;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 将输入流转换为字符串
	 * 
	 * @param input
	 *            输入流
	 * @return 转换后的字符串
	 */
	public static String inputToStr(InputStream input) {
		String result = "";
		if (input != null) {
			byte[] array = new byte[1024];
			StringBuffer buffer = new StringBuffer();
			try {
				for (int index; (index = (input.read(array))) > -1;) {
					buffer.append(new String(array, 0, index, "UTF-8"));
				}
				result = buffer.toString();
			} catch (IOException e) {
				e.printStackTrace();
				result = "";
			}
		}
		return result;
	}

	/*
	 * public static JSONObject httpRequest(String requestUrl, String requestMethod,
	 * String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new
	 * StringBuffer(); try { // 创建SSLContext对象，并使用我们指定的信任管理器初始化 TrustManager[] tm =
	 * { new MyX509TrustManager() }; SSLContext sslContext =
	 * SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new
	 * java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象
	 * SSLSocketFactory ssf = sslContext.getSocketFactory();
	 * 
	 * URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn =
	 * (HttpsURLConnection) url.openConnection();
	 * httpUrlConn.setSSLSocketFactory(ssf);
	 * 
	 * httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true);
	 * httpUrlConn.setUseCaches(false);
	 * 
	 * // 设置请求方式（GET/POST） httpUrlConn.setRequestMethod(requestMethod);
	 * 
	 * if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect();
	 * 
	 * // 当有数据需要提交时 if (null != outputStr) { OutputStream outputStream =
	 * httpUrlConn.getOutputStream(); // 注意编码格式，防止中文乱码
	 * outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); }
	 * 
	 * // 将返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream();
	 * InputStreamReader inputStreamReader = new InputStreamReader(inputStream,
	 * "utf-8"); BufferedReader bufferedReader = new
	 * BufferedReader(inputStreamReader);
	 * 
	 * String str = null; while ((str = bufferedReader.readLine()) != null) {
	 * buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); //
	 * 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect();
	 * jsonObject = JSONObject.parseObject(buffer.toString()); } catch
	 * (ConnectException ce) { } catch (Exception e) { } return jsonObject; }
	 */
}
